package com.yuzhenxin.bookstore.service;

import com.example.framework.common.exception.ServiceException;
import com.yuzhenxin.bookstore.config.BookstoreErrorCodeConstants;
import com.yuzhenxin.bookstore.dao.OrderDao;
import com.yuzhenxin.bookstore.domain.Order;
import com.yuzhenxin.bookstore.tools.jdbc.JdbcUtils;

import java.sql.SQLException;
import java.util.List;

public class OrderService {

    private final OrderDao orderDao = new OrderDao();

    /**
     * 添加订单
     * 处理事务
     */
    public void add(Order order) {
        try {
            // 开启事务
            JdbcUtils.beginTransaction();

            orderDao.addOrder(order);
            orderDao.addOrderItemList(order.getOrderItemList());

            // 提交事务
            JdbcUtils.commitTransaction();
        } catch (Exception e) {
            // 回滚事务
            try {
                JdbcUtils.rollbackTransaction();
            } catch (SQLException ignored) {
            }
            throw new RuntimeException(e);
        }
    }

    /**
     * 我的订单
     */
    public List<Order> myOrders(String uid) {
        return orderDao.findByUid(uid);
    }

    /**
     * 加载订单
     */
    public Order load(String oid) {
        return orderDao.load(oid);
    }

    /**
     * 确认收货
     */
    public void confirm(String oid) {
        int state = orderDao.getStateByOid(oid);
        if (state != 3) {
            throw ServiceException.of(BookstoreErrorCodeConstants.ORDER_CONFIRM_ERROR);
        }
        orderDao.updateState(oid, 4);
    }
}
